﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;


namespace Smtp_server
{
    public class Logger : Smtp_server.ILogger
    {
        private String pathFile = "log1.txt";

        //Lock : only one thread at time cans write into the file
        private System.Object lockThis = new System.Object();


        public Logger() 
        {
        }  

        public void Write(String text) 
        { 
             // write a line of text to the file
            lock (lockThis)
            {
                // create a writer and open the file
                StreamWriter sw = new StreamWriter(pathFile,true);
                sw.Write(text);
                sw.Flush();
                sw.Close();
            }
        }
        public String Read()
        {
            String text;

            // create a reader and open the file
            StreamReader sr = new StreamReader(pathFile);

            // read all line of text to the file
            text = sr.ReadToEnd();

            // close the stream
            sr.Close();

            return text;
        }
        public String ReadLast100()
        {
            String text;
            long pos;

            // create a reader and open the file
            StreamReader sr = new StreamReader(pathFile);

            // read all line of text to the file
            //i=0;
            //while (!sr.EndOfStream) { sr.Read(); i++; }

           
            pos = sr.BaseStream.Length - 100;
            if (pos<0)
                pos=0;
            sr.BaseStream.Seek(pos,SeekOrigin.Begin);

            text = sr.ReadToEnd();
            
            // close the stream
            sr.Close();

            return text;
        }
        public void Clear() 
        {
            lock (lockThis)
            {
                // create a writer and open the file
                StreamWriter sr = new StreamWriter(pathFile, false);
                sr.Close();
            }
            
        }

    }
}
